﻿using FastData.Caching;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Linq.Mapping;
using System.Reflection;
using System.Linq;
using System.ComponentModel.DataAnnotations;

namespace FastData
{
    public class InsertQuery<T> : QueryBase<T> where T : new()
    {
        private T _entity;
        private PropertyInfo _id;

        internal InsertQuery(DataAccess data, T entity)
            : base(data)
        {
            _entity = entity;

            foreach (PropertyInfo prop in typeof(T).GetDataProperties())
            {
                if (prop.IsKey())
                {
                    _id = prop;
                }
                else
                {
                    AddField(prop.Name, prop.GetValue(entity), true);
                }
            }
        }

        internal override string GetCommandText(ExecuteType type)
        {
            return Data.Provider.CreateInsertText(this, type);
        }

        public void ExecuteLazy()
        {
            Data.ExecuteLazy(this);
        }

        public int Execute()
        {
            return Data.ExecuteNonQuery(this);
        }

        public void ExecuteId()
        {
            object id;

            if (Data.Provider.SupportInsertedId)
            {
                IdName = _id.Name;
                id = Data.ExecuteScalar(this);
            }
            else
            {
                Data.ExecuteNonQuery(this);
                id = Convert.ChangeType(Data.GetLastIdentity(), _id.PropertyType);
            }

            _id.SetValue(_entity, id);
        }

        internal override void ExecuteCompleted()
        {
            CacheProvider.Remove(new TableDependency(TableName));
        }

    }

}
